<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-08
 * Time: 15:32
 */

namespace app\api\controller;


use app\common\model\Course as CourseModel;
use app\common\model\CourseChoose;
use app\common\model\UserTourist;
use app\service\MsgService;

class Course extends Base
{

    public $userTouristModel;
    public $courseChooseModel;

    public function __construct()
    {
        parent::__construct();
        $this->userTouristModel = new UserTourist();
        $this->courseChooseModel = new CourseChoose();

    }

    /**
     * 课程列表
     * @return \think\response\Json
     */
    public function course()
    {
        if (request()->isPost()) {
            $sid = input('sid', 0);
            $page = input('page', 1);
            $size = input('size', 20);
            $where = '(type=1) or (start_time > "' . date("Y-m-d H:i:s") . '")';
            $course = CourseModel::getPage($where, $page, $size, 'is_select asc,type asc');
            if ($course) {
                foreach ($course as $key => $value) {
                    if ($value['type'] == 2) {
                        $course[$key]['end_time'] = date('H:i:s', $value['end_time']);
                    }
                    $choose_where['cid'] = $value['id'];
                    //当前日期
                    $sdefaultDate = date("Y-m-d");
                    $first = 1;
                    $w = date('w', strtotime($sdefaultDate));
                    $week_start = strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days');
                    $week_end = $week_start + 7 * 24 * 60 * 60;
                    $choose_where['update_time'] = [
                        ['>', $week_start],
                        ['<', $week_end]
                    ];
                    if ($sid) {
                        $choose_where['sid'] = $sid;
                    } else {
                        $choose_where['type'] = 2;
                    }
                    $select = CourseChoose::getOne($choose_where);
                    $course[$key]['select'] = $select ? true : false;

                }
            }
            return returnJson(200, '', $course);
        }
        return returnJson(202, '暂无记录');
    }

    /**
     *
     */
    public function choose_search()
    {
        if (request()->isPost()) {
            $data = input('');
            if ($this->member['grade_id'] == 1) {
                if ($data['cid']) {
                    $where = [
                        'c_id' => $data['cid'],
//                        'uid' => $this->uid
                    ];
                    $course = CourseModel::getOne(['id' => $data['cid']]);
                    if ($course['type'] == 1) {
                        //当前日期
                        $sdefaultDate = date("Y-m-d");
                        $first = 1;
                        $w = date('w', strtotime($sdefaultDate));
                        $week_start = strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days');
                        $week_end = $week_start + 7 * 24 * 60 * 60;
                        $where['update_time'] = [
                            ['>', $week_start],
                            ['<', $week_end]
                        ];
                    }
                    $tourist = UserTourist::getOne($where);
                    if ($tourist) {
                        if ($tourist['is_examine'] == 1) {

                            $data['sid'] = $tourist['id'];
                            $res = $this->choose($data, 2);
                            return returnJson($res[0], $res[1]);

                        } else if ($tourist['is_examine'] == 0) {
                            return returnJson(202, '信息审核中...');
                        }
                    }
                    return returnJson(200, '', true);


                } else {
                    return returnJson(202, '课程错误');
                }
            } else {
                if ($data['cid']) {
                    $res = $this->choose($data);
                    return returnJson($res[0], $res[1]);
                }
            }
        }
    }

    /**
     * 等级队员信息
     * @return \think\response\Json
     */
    public function tourist()
    {
        if (request()->isPost()) {
            $data = input('');
            if ($data) {
                unset($data['mall_id']);
                unset($data['session_token']);
                $data['update_time'] = time();
                $data['uid'] = $this->uid;

                $where = [
                    'c_id' => $data['c_id'],
                    'uid' => $this->uid
                ];
                $course = CourseModel::getOne(['id' => $data['c_id']]);
                if ($course['type'] == 1) {
                    //当前日期
                    $sdefaultDate = date("Y-m-d");
                    $first = 1;
                    $w = date('w', strtotime($sdefaultDate));
                    $week_start = strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days');
                    $week_end = $week_start + 7 * 24 * 60 * 60;
                    $where['update_time'] = [
                        ['>', $week_start],
                        ['<', $week_end]
                    ];
                }
                $tourist = UserTourist::getOne($where);
                if ($tourist) {
                    $res = UserTourist::update($data, ['id' => $tourist['id']]);
                } else {
                    $data['create_time'] = time();
                    $res = UserTourist::create($data);
                }

                if ($res) {
                    //新增选课通知管理员
                    $course_manager = explode(',', config('course_manager'));
                    if ($course_manager && is_array($course_manager)) {
                        foreach ($course_manager as $value) {
                            $data['course'] = $course['title'];
                            $data['course_id'] = $course['id'];
                            $data['id'] = $res;
                            $data['first'] = '选课登记信息审核通知';
                            $data['remark'] = "有新的游客选课信息提交审核。\n联系人：".$data['contact']."\n联系方式：".$data['phone'];
                            MsgService::S()->sendTemp(MsgService::$tempType_NEW_COURSE_REGISTER, $this->mall_id, $value, $data);
                        }
                    }
                    return returnJson(200, '已经成功提交，稍后跟您联系。');
                } else {
                    return returnJson(202, '信息登记失败');
                }

            }
            return returnJson(202, '信息不完整');
        }
    }

    /**
     * 取消选课
     * @return \think\response\Json
     */
    public function choose_unset()
    {
        if (request()->isPost()) {
            $data = input('');
            if ($data['cid'] && ($this->member['grade_id'] == 1 or ($data['sid']))) {
                $where = [
                    'cid' => $data['cid'],
                ];
                if ($data['sid']) {
                    $where['sid'] = $data['sid'];
                }else{
                    $where['uid'] = $this->uid;
                    $where['type'] = 2;
                }
                $course_choose = CourseChoose::getOne($where);
                if ($course_choose) {
                    $this->courseChooseModel->where($where)->delete();
                    $this->userTouristModel->where(['c_id' => $data['cid'], 'uid' => $this->uid])->delete();
                    \app\common\model\Course::setIncr(['id' => $data['cid']], 'num');
                    \app\common\model\Course::update(['is_select' => 1, 'update_time' => time()], ['id' => $data['cid']]);
                }

            }
        }
        return returnJson(200, '已成功取消选课');
    }

    /**
     * 选课
     * @param $data
     * @param int $type
     * @return \think\response\Json
     */
    private function choose($data, $type = 1)
    {
        if ($data) {
            $where = [
                'uid' => $this->uid,
                'sid' => $data['sid'],
                'cid' => $data['cid'],
                'type' => $type
            ];
            $course = CourseModel::getOne(['id' => $data['cid']]);
            if ($course['type'] == 1) {
                //当前日期
                $sdefaultDate = date("Y-m-d");
                $first = 1;
                $w = date('w', strtotime($sdefaultDate));
                $week_start = strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days');
                $week_end = $week_start + 7 * 24 * 60 * 60;
                $where['update_time'] = [
                    ['>', $week_start],
                    ['<', $week_end]
                ];
            }
            $res = CourseChoose::getOne($where);
            if ($res) {
                return [202, '已选过该课程'];
            } else {
                $where['create_time'] = time();
                $where['update_time'] = time();
                $num = $course['num'] - 1;
                if ($num >= 0) {
                    $save_res = CourseChoose::create($where);
                    $course_data = [
                        'num' => $num,
                        'is_select' => $num == 0 ? 2 : 1,
                    ];
                    CourseModel::update($course_data, ['id' => $course['id']]);
                    if ($save_res) {
                        return array(203, '选课成功');
                    } else {
                        return array(202, '选课失败');
                    }
                }
            }
        }
    }

}